package com.smasher.core.other;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import com.smasher.core.io.FileUtil;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;

public class CrashHandler implements Thread.UncaughtExceptionHandler {


    public static final String TAG = "CrashHandler";
    /**
     * 系统默认的UncaughtException处理类
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    /**
     * CrashHandler实例
     */
    @SuppressLint("StaticFieldLeak")
    private static CrashHandler INSTANCE;


    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler() {
    }


    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new CrashHandler();
        }
        return INSTANCE;
    }


    /**
     * 程序的Context对象
     */
    private Context mContext;


    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
        try {
            boolean handled = handleException(e);
        } catch (Exception ex) {
            Log.e(TAG, "uncaughtException: ", ex);
        }
        if (mDefaultHandler != null) {
            mDefaultHandler.uncaughtException(t, e);
        }
    }

    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 收集设备参数信息
        // 保存日志文件
        String fileName = saveCrashInfoToFile(ex);
        Log.e(TAG, "handleException: " + fileName);
        return true;
    }

    private String saveCrashInfoToFile(Throwable ex) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        Date date = new Date(System.currentTimeMillis());
        String result = date.toString() + info;
        printWriter.close();


        Log.d(TAG, "Crash message: " + ex.getMessage());
        Log.d(TAG, "Crash type: " + ex.getClass().getName());
        Log.d(TAG, "Crash localizedMessage: " + ex.getLocalizedMessage());

        String typeEx = ex.getClass().getSimpleName();
        long time = System.currentTimeMillis();

        StringBuilder stringBuilder = new StringBuilder(LABEL);
        stringBuilder.append("_");
        stringBuilder.append(typeEx);
        stringBuilder.append("_");
        stringBuilder.append(time);
        stringBuilder.append(".log");

        String fileName = stringBuilder.toString();
        File parent = mContext.getExternalFilesDir("LOG");
        File target = new File(parent, fileName);
        FileUtil.createFile(target, true);
        FileUtil.saveFile(target, result);

        return target.getAbsolutePath();
    }

    public static final String LABEL = "crash";
}
